package com.hj.reggie.common;

import com.hj.reggie.domain.Dish;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 处理数据校验模板
 *
 * @author 37460
 */
public class ValidationUtil {
    private static Validator validator;

    static {
        //创建Validator验证器对象
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    public static R<List<String>> valid(Dish dish, Class<?>... groups) {
        //如果被校验对象userInfo没有检验通过，则set里面就有校验信息，返回出去
        Set<ConstraintViolation<Dish>> set = validator.validate(dish, groups);
        List<String> list = set.stream().map(v -> "属性：" + v.getPropertyPath() + "，属性值是：" + v.getInvalidValue() + "，校验不通过的提示信息：" + v.getMessage() + "，消息模板：" + v.getMessageTemplate()).collect(Collectors.toList());
        return R.error(list.get(1));
    }

    public static void main(String[] args) {
//        Dish dish = new Dish("黄金");

    }
}
